﻿using MQTTnet.Client;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;
using Microsoft.Extensions.Options;
using MQTTnet.Server;
using MQTTnet.Client.Options;

namespace Himp.TaskScheduling
{
    public static class MqttClientHelper
    {
        private static string Ip = "112.33.111.160";
        private static int Port = 8084;
        private static object _locker = new Object();
        private static IMqttClient _instance = null;

        /// <summary>
        /// 使用一个静态属性来返回已连接的实例，如下列中所示。这样，一旦 ConnectionMultiplexer 断开连接，便可以初始化新的连接实例。
        /// </summary>
        public static IMqttClient Instance
        {
            get
            {
                if (Ip.Length == 0)
                {
                    throw new Exception("连接字符串未设置！");
                }

                if (_instance == null)
                {
                    lock (_locker)
                    {
                        if (_instance == null || !_instance.IsConnected)
                        {
                            // 创建客户端配置
                            var options = new MqttClientOptionsBuilder()
                                .WithTcpServer(Ip, Port)
                                .WithClientId("TaskScheduling") // 客户端ID
                                .Build();

                            _instance = new MqttFactory().CreateMqttClient();

                            _instance.UseConnectedHandler(e =>
                            {
                                Console.WriteLine("Connected to MQTT Broker");
                            });

                            // 处理连接断开事件
                            _instance.UseDisconnectedHandler(e =>
                            {
                                Console.WriteLine("Disconnected from MQTT Broker");
                                // 连接到MQTT服务器
                                _instance.ConnectAsync(options, CancellationToken.None);
                            });

                            // 处理接收到消息事件
                            _instance.UseApplicationMessageReceivedHandler(e =>
                            {
                                Console.WriteLine($"Received message: {e.ApplicationMessage.Payload}");
                            });

                            // 连接到MQTT服务器
                            _instance.ConnectAsync(options, CancellationToken.None);
                        }
                    }
                }

                return _instance;
            }
        }

        static MqttClientHelper()
        {
        }

        public static async Task PublishStringAsync(string topic,string cont)
        {
            var message1 = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(cont)
                .WithRetainFlag()
                .Build();
            await Instance.PublishAsync(message1, CancellationToken.None);
        }
    }
}
